import request from "@/utils/request"
import { userActionType } from "@/store/modules/user"
import { cloneDeep } from "@/utils"

export const vocabularyLearningActionType = {
  getters: {
    planInfo: "vocabularyLearning/planInfo",
    planId: "vocabularyLearning/planId",
    vocabularyDetail: "vocabularyLearning/vocabularyDetail",
  },
  mutations: {
    planInfo: "vocabularyLearning/planInfo",
    planId: "vocabularyLearning/planId",
    vocabularyDetail: "vocabularyLearning/vocabularyDetail",
  },
  actions: {
    planInfo: "vocabularyLearning/planInfo",
  },
}

const planInfoTemplate = {
  planId: 0,
  userId: "",
  examId: 0,
  thesaurusId: 0,
  dailyWordCount: 0,
  currentDay: 0,
  practiceMode: "",
  currentlyStudying: 0,
  createTime: "",
  thesaurusName: "",
  thesaurusImg: "",
  thesaurusNotes: "",
  thesaurusNum: 0,
  studyWordNum: 0,
  isCurrentDayStudying: false,
  learnWordCount: 0,
  unreviewedWordCount: 0
}
export default {
  namespaced: false,
  state: {
    planInfo: cloneDeep(planInfoTemplate),
    vocabularyDetail: null,
    planId: "",
  },
  getters: {
    [vocabularyLearningActionType.getters.planInfo]: (state) => state.planInfo,
    [vocabularyLearningActionType.getters.vocabularyDetail]: (state) => state.vocabularyDetail,
    [vocabularyLearningActionType.getters.planId]: (state) => state.planInfo.planId,
  },
  mutations: {
    [vocabularyLearningActionType.mutations.planInfo](state, planInfo) {
      state.planInfo = planInfo
      if (planInfo) {
        state.planId = planInfo.planId
      }
    },
    [vocabularyLearningActionType.mutations.vocabularyDetail](state, vocabularyDetail) {
      state.vocabularyDetail = vocabularyDetail
    },
    [vocabularyLearningActionType.mutations.planId](state, planId) {
      state.planId = planId
    }
  },
  actions: {
    // 获取并刷新用户当前的计划信息
    // params.showLoading 是否显示loading；params.jumpToSelectExam 是否跳转到选择考试页面
    [vocabularyLearningActionType.actions.planInfo]: async (store,  params = {}) => {
      params.showLoading && uni.showLoading({ title: "加载中" })
      const userSelectExamId = store.getters[userActionType.getters.userSelectExamId]
      if (params.jumpToSelectExam && !userSelectExamId) {
        uni.hideLoading()
        uni.navigateTo({ url: "/pages/examSelection/index" })
        return
      }
      const planInfo = await request({
        url: "userCheckPlan/getUserCurrentlyPlan",
        data: {
          examId: userSelectExamId,
        },
        errorHandle: true,
      })
      params.showLoading && uni.hideLoading()
      if (planInfo) {
        store.commit(vocabularyLearningActionType.mutations.planInfo, planInfo)
      } else {
        store.commit(vocabularyLearningActionType.mutations.planInfo, cloneDeep(planInfoTemplate))
      }
      return planInfo
    },
  },
}
